<template>
  <!-- 授权用户 -->
  <el-dialog :close-on-click-modal="false" title="选择用户" v-model="visible" :destroy-on-close="true" :width="600">
    <div class="layout-main">
      <div class="layout-left">
        <el-tabs v-model="activeTabs" type="border-card">
          <el-tab-pane label="用户" name="user">
            <el-input v-model="userFilterText" placeholder="搜索关键字" />
            <el-tree
                ref="user-tree"
                :props="treeProps"
                :data="userTreeData"
                :default-checked-keys="defaultCheckedKeys"
                node-key="nodeKey"
                show-checkbox
                :check-strictly="true"
                :render-after-expand="false"
                :filter-node-method="filterNode"
                @check-change="handleCheckChange"
            />
          </el-tab-pane>
          <el-tab-pane label="角色" name="role" v-if="props.enableRole">
            <el-input v-model="roleFilterText" placeholder="搜索关键字" />
            <el-tree
                ref="role-tree"
                :data="roleListData"
                :default-checked-keys="defaultCheckedKeys"
                node-key="nodeKey"
                show-checkbox
                :check-strictly="true"
                :render-after-expand="false"
                :filter-node-method="filterNode"
                @check-change="handleCheckChange"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="layout-right">
        <el-collapse v-model="activeCollapse">
          <el-collapse-item name="user">
            <template #title>
              <div class="selected-title">已选用户</div>
            </template>
            <template v-for="item in result">
              <div v-if="item.type == 'user'" class="selected-item">
                <div class="selected-item-name">{{item.label}}</div>
                <div class="selected-item-close" @click="handleUnselect(item)"><el-icon><Close /></el-icon></div>
              </div>
            </template>
          </el-collapse-item>
          <el-collapse-item name="dept" v-if="props.enableDept">
            <template #title>
              <div class="selected-title">已选部门</div>
            </template>
            <template v-for="item in result">
              <div v-if="enableDept && item.type == 'dept'" class="selected-item">
                <div class="selected-item-name">{{item.label}}</div>
                <div class="selected-item-close" @click="handleUnselect(item)"><el-icon><Close /></el-icon></div>
              </div>
            </template>
          </el-collapse-item>
          <el-collapse-item name="role" v-if="props.enableRole">
            <template #title>
              <div class="selected-title">已选角色</div>
            </template>
            <template v-for="item in result">
              <div v-if="enableRole && item.type == 'role'" class="selected-item">
                <div class="selected-item-name">{{item.label}}</div>
                <div class="selected-item-close" @click="handleUnselect(item)"><el-icon><Close /></el-icon></div>
              </div>
            </template>
          </el-collapse-item>
        </el-collapse>
      </div>

    </div>
    <template #footer>
       <div class="dialog-footer">
         <el-button type="primary" @click="handleSelectUser">确 定</el-button>
         <el-button @click="visible = false">取 消</el-button>
       </div>
    </template>
  </el-dialog>
</template>

<script setup name="UserSelect">
import { userTree } from "@/api/system/user";
import { roleNodeList } from "@/api/system/role";
import {onMounted, watch} from "vue";

const props = defineProps({
  modelValue: {
    type: Array,
    default: []
  },
  enableDept: { // 开启部门可选功能
    type: Boolean,
    default: false
  },
  enableRole: { // 开启角色可选功能
    type: Boolean,
    default: false
  },
  multipleSize: { // 多选数量，-1表示不限
    type: Number,
    default: -1
  },
});

const { proxy } = getCurrentInstance();

const activeTabs = ref('user')
const activeCollapse = ref(['user', 'dept', 'role'])
const userTreeData = ref([]);
const roleListData = ref([]);
const visible = ref(false);
const userFilterText = ref('')
const roleFilterText = ref('')
const defaultCheckedKeys = ref([])
const result = ref([]);

const treeProps = {
  children: 'children',
  label: 'label',
  disabled: (data, node) => {
    if(props.multipleSize > 0 && result.value.length == props.multipleSize) {
      return true
    }

    if(!props.enableDept && data.type == 'dept') {
      return true
    } else {
      return false
    }
  }
}

onMounted(() => {
  getUserTree();
  getRoleNodeList();
  init()
})

/** 监听modelValue值的变化 */
watch(() => props.modelValue, (newVal, oldVal) => {

});

watch(userFilterText, (val) => {
  if (proxy.$refs['user-tree'] != null) {
    proxy.$refs['user-tree'].filter(val)
  }

})
watch(roleFilterText, (val) => {
  if (proxy.$refs['role-tree'] != null) {
    proxy.$refs['role-tree'].filter(val)
  }
})

// 显示弹框
function show() {
  init()
  visible.value = true
}

/** 获取用户tree */
function getUserTree() {
  userTree().then(response => {
    userTreeData.value = response.data;
  })
}

/** 获取用户tree */
function getRoleNodeList() {
  roleNodeList().then(response => {
    roleListData.value = response.data;
  })
}

function filterNode(value, data) {
  if (!value) return true
  return data.label.includes(value)
}

// 节点选中事件处理
function handleCheckChange(data, checked, indeterminate) {
  let checkedData = [];
  let checkedUserData = handleCheckedNodes('user-tree')
  checkedData = checkedData.concat(checkedUserData)

  if(props.enableRole) {
    let checkedRoleData = handleCheckedNodes('role-tree')
    checkedData = checkedData.concat(checkedRoleData)
  }

  result.value = checkedData
}

function handleCheckedNodes(treeRef) {
  let data = proxy.$refs[treeRef].getCheckedNodes()
  let checkedData = [];

  data.map(item => {
    checkedData.push({
      id: item.id,
      nodeKey: item.nodeKey,
      type: item.type,
      label: item.label
    })
  })
  return checkedData;
}

// 取消选中
function handleUnselect(item) {
  if(item && item.nodeKey) {
    if(item.type == 'user' || item.type == 'dept') {
      proxy.$refs['user-tree'].setChecked(item.nodeKey, false)
    } else if(item.type == 'role') {
      proxy.$refs['role-tree'].setChecked(item.nodeKey, false)
    }
  }
}

function init() {
  userFilterText.value = ''
  roleFilterText.value = ''
  let data = props.modelValue
  let checkedKeys = []
  if(data && data.length > 0) {
    data.map(item => {
      if(item && item.type && item.id) {
        let nodeKey = `${item.type}-${item.id}`
        data.nodeKey = nodeKey
        checkedKeys.push(nodeKey)
      }
    })
  }
  defaultCheckedKeys.value = checkedKeys
  result.value = data
}

const emit = defineEmits(["ok"]);
/** 选择授权用户操作 */
function handleSelectUser() {
  visible.value = false;
  proxy.$emit("update:modelValue", result.value)
  emit("ok", result.value);
}

defineExpose({
  show
});
</script>

<style scoped lang="scss">
.layout-main {
  width: 100%;
  height: 400px;
  display: flex;
  flex-direction: row;

  .layout-left {
    flex: 1;
    overflow-y: auto;
  }

  .layout-right {
    flex: 1;
    border: 1px solid #dcdfe6;
    overflow-y: auto;
    padding: 0 20px;
    box-sizing: border-box;
    height: 100%;
  }
}

.el-tabs--border-card {
  height: 100% !important;
}

.selected-title {
  font-size: 14px;
  font-weight: bolder;
}
.selected-item {
  display: flex;
  flex-direction: row;
  height: 30px;
  align-items: center;

  .selected-item-name {
    padding-left: 10px;
    flex: 1;
  }
  .selected-item-close {
    width: 30px;
    cursor: pointer;
  }
}
</style>
